


  var token = getCookie("token");

var container = document.querySelector(".container");
    window.onload = function(){
      ajax({
            url : "http://127.0.0.1:8888/goods/list",
            data : { current : 5 , pagesize : 20},
            callback : render
      })
}

var bullets = document.querySelectorAll("#pagination li");
for(var i = 0 ; i < bullets.length ; i ++){
      bullets[i].onclick = function(){
            // this.innerHTML 表示获取页码
            // 分页; 
            ajax({
                  url : "http://127.0.0.1:8888/goods/list",
                  data : { current : this.innerHTML , pagesize : 20},
                  callback : render
            })
      }
}

function render( res ){
      res = JSON.parse(res);
      console.log(res);
      
      container.innerHTML = res.list.map( item => `<div class="goods">
            <img src="${ item.img_big_logo }" alt="">
            <h1>${ item.title }</h1>
            <h2>${ item.price }</h2>
            <p><button data-id="${item.goods_id}" class="btn btn-danger btn-small">加入购物车</button>
      </div>`).join("");
}     


  $(".container").on("click" , ".btn" , handlerAddCart )

  function handlerAddCart(){


    var user_id  = getCookie("userid");

    var goods_id = $(this).attr("data-id");
       
       console.log(user_id,goods_id);

    var options = {
        url:`http://127.0.0.1:8888/cart/add?id=${user_id}&goodsId=${goods_id}`,
        type:"POST",
        data:{
            id:user_id,
            goodsId :goods_id
        },
        headers:{
            authorization: token
        }
    }
    
    $.ajax(options)
    .done(function(data){
       console.log(data);
       handlerAjax(data);

    })
  
 };

   function handlerAjax(data){
       switch(data.code){
           case 1:
               alert("已加入到您的购物车");
               break;
            case 401 :
                alert("请先登录");
                break;
            }
   };
   




